package com.example.loginmvvm.player

import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.Observer
import com.example.loginmvvm.R
import com.example.loginmvvm.base.BaseActivity
import com.example.loginmvvm.musicList.MusicPresenter
import kotlinx.android.synthetic.main.activity_player.*

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/4/19.
 * PS: Not easy to write code, please indicate.
 */
class PlayerActivity : BaseActivity() {

    private val musicPresenter by lazy {
        MusicPresenter(this)
    }

    private val playerPresenter by lazy {
        PlayerPresenter.instance
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_player)
        initDataListener()
        initListener()
    }

    private fun initListener() {
        btn_player.setOnClickListener {
            playerPresenter.doPlayOrPause()
        }

        btn_previous.setOnClickListener {
            playerPresenter.playNext()
        }

        btn_next.setOnClickListener {
            playerPresenter.playPre()
        }

        iv_cover.setOnClickListener {
            startActivity(Intent(this, FlowPlayerControllerActivity::class.java))
        }
    }

    private val livePlayerObserver by lazy {
        LivePlayerStateObserver()
    }

    class LivePlayerStateObserver : Observer<PlayerPresenter.PlayState> {
        override fun onChanged(t: PlayerPresenter.PlayState?) {
            println("PlayerActivity播放器界面...live data...>当前的状态$t")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LivePlayerState.instance.removeObserver(livePlayerObserver)
    }

    /**
     * 对数据进行监听
     */
    private fun initDataListener() {
        LivePlayerState.instance.observeForever(livePlayerObserver)

        playerPresenter.currentMusic.addListener(this) {
            //音乐内容发生变化了，更新ui
            tv_title.text = it?.name
            println("封面改变了...${it?.cover}")
        }
        playerPresenter.currentPlayState.addListener(this) {
            when (it) {
                PlayerPresenter.PlayState.PAUSE -> {
                    btn_player.text = "播放"
                }
                PlayerPresenter.PlayState.PLAYING -> {
                    btn_player.text = "暂停"
                }
            }
        }
    }
}